package com.cbtx.networklib.ssl

import android.util.Log
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.NoSuchProviderException
import java.security.SignatureException
import java.security.cert.CertificateException
import java.security.cert.CertificateExpiredException
import java.security.cert.CertificateNotYetValidException
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/29 1:06 PM
 * desc   :
 */
class MyX509TrustManager : X509TrustManager {
    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {

    }

    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        if (chain != null) {
            for (cert in chain) {
                try {
                    // 验证证书是否有效
                    cert.checkValidity()
                } catch (e: CertificateExpiredException) {
                    //此异常是证书已经过期异常，在手机调到证书生效时间之后会捕捉到此异常
                    Log.e("Err", "checkServerTrusted: CertificateExpiredException:" + e.localizedMessage)
                } catch (e: CertificateNotYetValidException) {
                    //此异常是证书未生效异常，在手机调到证书生效时间之前会捕捉到此异常
                    Log.e("Err", "checkServerTrusted: CertificateNotYetValidException:" + e.localizedMessage)
                }
                try {
                    // 验证密钥
                    cert.verify(cert.publicKey)
                } catch (e: CertificateExpiredException) {
                    //此异常是证书已经过期异常，在手机调到证书生效时间之后会捕捉到此异常
                    Log.e("Err", "checkServerTrusted: CertificateExpiredException:" + e.localizedMessage)
                } catch (e: CertificateNotYetValidException) {
                    //此异常是证书未生效异常，在手机调到证书生效时间之前会捕捉到此异常
                    Log.e("Err", "checkServerTrusted: CertificateNotYetValidException:" + e.localizedMessage)
                } catch (ex: CertificateException) {
                    //其他异常正常报错
                    Log.e("Err", "Throw checkClientTrusted: " + ex.localizedMessage)
                    throw ex
                } catch (e: NoSuchAlgorithmException) {
                    Log.e("Err", "checkServerTrusted: NoSuchAlgorithmException:" + e.localizedMessage)
                } catch (e: InvalidKeyException) {
                    Log.e("Err", "checkServerTrusted: InvalidKeyException:" + e.localizedMessage)
                } catch (e: NoSuchProviderException) {
                    Log.e("Err", "checkServerTrusted: NoSuchProviderException:" + e.localizedMessage)
                } catch (e: SignatureException) {
                    Log.e("Err", "checkServerTrusted: SignatureException:" + e.localizedMessage)
                }
            }
        }
    }

    override fun getAcceptedIssuers(): Array<X509Certificate> {
        return arrayOf()
    }
}
